#views.py
#this is the views file for sanjhachoolha

import os
import re

import django

from google.appengine.api import users
from google.appengine.ext import db
from google.appengine.ext.db import djangoforms#unncessary
from django import http
from django import shortcuts
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse

from django import newforms as forms #will be changed in newer django 
from sanjhachoolha.models import * #change the format of this import
from django.utils.translation import gettext
from django.newforms.util import ErrorList, ValidationError, smart_unicode

# ########Regexps begins
wordregex = "^[a-zA-Z0-9\\-\'\. ]+$"
emailregex = "^[a-zA-Z0-9\_\.]{3,}\@[a-zA-Z0-9\_\.]{3,}$"
# ###regexps ends

# ########Classes Begin
class CSVField(forms.Field):
    def __init__(self, regex, max_length=None, min_length=None, error_message=None, *args, **kwargs):
        """
        regex can be either a string or a compiled regular expression object.
        error_message is an optional error message to use, if
        'Enter a valid value' is too generic for you.
        """
        super(CSVField, self).__init__(*args, **kwargs)
        if isinstance(regex, basestring):
            regex = re.compile(regex)
        self.regex = regex
        self.max_length, self.min_length = max_length, min_length
        self.error_message = error_message or gettext(u'Enter a valid value.')

    def clean(self, value):
        """
        Validates that the csv attributes matches the regular expression. Returns a
        Unicode object.
        """
        super(CSVField, self).clean(value)
        
        if value == u'':
            return value
        if self.max_length is not None and len(value) > self.max_length:
            raise ValidationError(gettext(u'Ensure this value has at most %d characters.') % self.max_length)
        if self.min_length is not None and len(value) < self.min_length:
            raise ValidationError(gettext(u'Ensure this value has at least %d characters.') % self.min_length)

        value = value.lower()
        value = list(set(re.split('^\s*|\s*,+\s*|\s*$', value)))
        if (value[0] == ''):
            value.remove('')
        for var in value:
            if not self.regex.search(var):
                raise ValidationError(self.error_message)
        return value
    
    
class ActonForm(forms.Form):
    creator = forms.RegexField(wordregex, max_length=30, min_length=3)
    #creationTime--will be auto added
    category = CSVField('^[a-zA-Z0-9\\-\'\. ]+$', max_length=100)#csv field
    priority = forms.ChoiceField(widget=forms.RadioSelect, choices=(('low', 'Low'),
                                        ('medium', 'Medium'),
                                        ('high', 'High'),
                                        ('urgent', 'Urgent'),
                                        ))
    tags = CSVField(wordregex, max_length=100)#csv field
    title = forms.CharField(max_length=100)#for field we can use a label attr
    description = forms.CharField(widget=forms.Textarea(attrs={'rows':"10"}), initial='Describe your acton')
    skills = CSVField(wordregex, max_length=100)#csv field
    eta = forms.DateTimeField(input_formats=['%m/%d/%Y %H:%M'], initial='7/25/2009 14:30')
    timeNeeded = forms.TimeField(input_formats=['%H:%M'], initial='14:30', label="Time Needed")
    coordinators = CSVField(emailregex)#csv email field
    #subscribers
    #actors
    status = forms.ChoiceField(widget=forms.RadioSelect, choices=(('new', 'New'),
                                        ('assigned', 'Assigned'),
                                        ('closed', 'Closed'),
                                        ('modified', 'Modified'),
                                        ('verified', 'Verified'),
                                        ('deleted', 'Deleted'),
                                        ))

####Classes end

########utility functions begin

##"-".join(re.findall("\w+", " killer be @dam$$$ hell? ?"))

####utility functions end
def respond(request, user, template, params=None):
  """Helper to render a response, passing standard stuff to the response.

  Args:
    request: The request object.
    user: The User object representing the current user; or None if nobody
      is logged in.
    template: The template name; '.html' is appended automatically.
    params: A dict giving the template parameters; modified in-place.

  Returns:
    Whatever render_to_response(template, params) returns.

  Raises:
    Whatever render_to_response(template, params) raises.
  """
  if params is None:
    params = {}
  if user:
    params['user'] = user
    params['sign_out'] = users.create_logout_url('/')
    params['is_admin'] = (users.is_current_user_admin() and
                          'Dev' in os.getenv('SERVER_SOFTWARE'))
  else:
    params['sign_in'] = users.create_login_url(request.path)
  if not template.endswith('.html'):
    template += '.html'
  return shortcuts.render_to_response(template, params)



def index(request):
  """show index"""
  responseText = """Hello, world. This shows the main acton index. Please try the following urls, based on\
  <a href="http://code.google.com/p/sanjhachoolha/wiki/URLPatterns"\
  target="_blank">http://code.google.com/p/sanjhachoolha/wiki/URLPatterns</a><br/>\
  For URLs with numbers (like 25 and 44), try changing them, and see what happens<br/>\
  <ul>\
  <li><a href="/sanjhachoolha/acton/add">/sanjhachoolha/acton/add</a></li>\
  <li><a href="/sanjhachoolha/acton/25">/sanjhachoolha/acton/25</a></li>\
  <li><a href="/sanjhachoolha/acton/25/edit">/sanjhachoolha/acton/25/edit</a></li>\
  <li><a href="/sanjhachoolha/acton/25/subscribe">/sanjhachoolha/acton/25/subscribe</a></li>\
  <li><a href="/sanjhachoolha/acton/25/unsubscribe">/sanjhachoolha/acton/25/unsubscribe</a></li>\
  <li><a href="/sanjhachoolha/acton/25/signup">/sanjhachoolha/acton/25/signup</a></li>\
  <li><a href="/sanjhachoolha/acton/25/leave">/sanjhachoolha/acton/25/leave</a></li>\
  <li><a href="/sanjhachoolha/acton/25/comments/add">/sanjhachoolha/acton/25/comments/add</a></li>\
  <li><a href="/sanjhachoolha/acton/25/comments/44/delete">/sanjhachoolha/acton/25/comments/44/delete</a></li>\
  <li><a href="/sanjhachoolha/search">/sanjhachoolha/search</a></li>\
  <li><a href="/sanjhachoolha/list">/sanjhachoolha/list</a></li>\
  </ul>\
  """
  return respond(request, None, 'sc-base', {'content': responseText})

####add() begins  
def add(request):
    """add Acton to database  """
    
    if request.method == 'POST': # If the form has been submitted...
        form = ActonForm(request.POST) # A form bound to the POST data
        
        if form.is_valid(): # All validation rules pass
            
            # Process the data in form.cleaned_data
            # ...
            
            acton=Acton()
            acton.creator = form.clean_data['creator']
            for category in form.clean_data['category']:
                c = Category(name=category)
                acton.category.append(c.put())  # docs/datastore/functions#put()
            acton.priority = form.clean_data['priority']
            for tag in form.clean_data['tags']:
                c = Tags(name=tag)
                acton.tags.append(c.put())
            acton.title = form.clean_data['title']
            acton.description = form.clean_data['description']
            for skill in form.clean_data['skills']:
                c= Skills(name=skill)
                acton.skills.append(c.put())
            acton.eta = form.clean_data['eta']
            acton.timeNeeded = form.clean_data['timeNeeded']
#            for coordinator in form.clean_data['coordinators']:
#                c = SCUser.gql("WHERE user = :1",).get()
#                acton.coordinators.append(c) ##will this work??
            
            acton.slug = "-".join(re.findall("\w+", acton.title))
            acton_id = acton.put().id()

            return HttpResponseRedirect(reverse('sanjhachoolha.views.show', kwargs= {'slug': acton.slug,
                                                                                     'acton_id':acton_id, }))

    else:
        form = ActonForm() # An unbound form

    return shortcuts.render_to_response('sc-actonform.html', {
        'form': form,
    })
    
###add() ends    
      
def show(request, acton_id, slug):
    """show acton with with acton_id"""
    #acton=Acton.gql("WHERE slug = :1", slug).get()
    acton = Acton.get_by_id(int(acton_id))
    c=[]
    for categoryKey in acton.category:
        category = Category.get(categoryKey)
        c.append(category.name)
    
    
    return shortcuts.render_to_response('sc-actonshow.html', {'acton':acton,
                                                              'categories':c,
                                                              'id': acton_id,
                                                              
                                                              })
  


def edit(request, acton_id):
  """adds an acton"""
  responseText = "Hello, world. This will edit acton with ID " + acton_id
  return respond(request, None, 'sc-base', {'content': responseText})

#note - to sign up is to actually work on an acton. To subscribe is to simply follow  
def subscribe(request, acton_id):
  """subscribes user to an acton"""
  responseText = "Hello, world. This will subscribe current user to acton with ID " + acton_id
  return respond(request, None, 'sc-base', {'content': responseText})

def unsubscribe(request, acton_id):
  """unsubscribes user from an acton"""
  responseText = "Hello, world. This will unsubscribe current user from acton with ID " + acton_id
  return respond(request, None, 'sc-base', {'content': responseText})

def signup(request, acton_id):
  """signup user to work for an acton"""
  responseText = "Hello, world. This will signup current user to work for acton with ID " + acton_id
  return respond(request, None, 'sc-base', {'content': responseText})

def leave(request, acton_id):
  """allowes user to stop working on an acton"""
  responseText = "Hello, world. This will allow current user to stop working on acton with ID " + acton_id
  return respond(request, None, 'sc-base', {'content': responseText})

def add_comment(request, acton_id):
  """add a new comment"""
  responseText = "Hello, world. This will add a new comment to acton with ID " + acton_id
  return respond(request, None, 'sc-base', {'content': responseText})
  
def delete_comment(request, acton_id, comment_id):
  """add a new comment"""
  responseText = "Hello, world. This will delete comment with ID " + comment_id + " from acton with ID " + acton_id
  return respond(request, None, 'sc-base', {'content': responseText})

def search(request):
  """show search"""
  responseText = "Hello, world. This shows the main search page."
  return respond(request, None, 'sc-base', {'content': responseText})
  
def listall(request):
  """show list of all actons"""
  responseText = "Hello, world. This shows a list of all actons. Best intended to be used by search engines."
  return respond(request, None, 'sc-base', {'content': responseText})
  
